<?php

namespace App\Traits;

use App\Exceptions\HttpException;
use App\Utils\ErrCode;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;

trait ControllerTrait
{
    /**
     * @param array $data
     * @return JsonResponse
     */
    public function success($data = []): JsonResponse
    {
        return response()->json([
            'code' => 0,
            'data' => $data
        ]);
    }

    /**
     * @param string| \Exception $messageOrException
     * @param int $code
     * @param int $status
     * @return JsonResponse
     */
    public function error($messageOrException = 'error', $code = ErrCode::UNKNOWN_ERR,  $status = 400): JsonResponse
    {
        if ($messageOrException instanceof QueryException) {
            return  response()->json([
                'code' => $messageOrException->getPrevious()->errorInfo[1],
                'message' => config('app.debug') ? $messageOrException->getMessage() : '数据库发生错误'
            ], 500);
        }

        if ($messageOrException instanceof \Exception || $messageOrException instanceof HttpException) {
            return response()->json([
                'code' => $messageOrException->getCode() ?: $code,
                'message' => $messageOrException->getMessage()
            ], method_exists($messageOrException, 'getStatusCode') ? $messageOrException->getStatusCode() : $status);
        }

        return response()->json([
            'code' => $code,
            'message' => $messageOrException
        ], $status);
    }
}
